import time
from typing import Optional

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import JSONResponse
from pydantic import BaseModel
# 确保你已经从 app.api.endpoints 导入了这两个路由
from app.api.endpoints import kb_chat, chat
from fastapi.responses import FileResponse  # 导入 FileResponse
app = FastAPI(
    title="LLM Application Scaffold - Separated Endpoints",
    description="An API with distinct, stateful endpoints for Knowledge Base (RAG) chat and Agent (Tool-calling) chat.",
    version="2.2.0",
)

# --- CORS 配置  ---
origins = [
    "http://localhost",
    "http://localhost:5500",
    "http://127.0.0.1",
    "http://127.0.0.1:8000"
]
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源，开发时最方便
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法，包括 OPTIONS
    allow_headers=["*"],  # 允许所有请求头
)
# --- 结束 CORS 配置 ---

@app.get("/", tags=["Health Check"])
def read_root():
    # return {"status": "ok", "message": "Welcome to the LLM Chat API!"}
    return FileResponse(r'C:\Users\10664\Desktop\LLM\frontend\index.html')

class KBChatPayload(BaseModel):
    # 'query' 字段是必需的，类型是字符串
    query: str
    # 'conversation_id' 是可选的，可以是字符串或 None
    conversation_id: Optional[str] = None

class AgentChatPayload(BaseModel):
    # 'input' 字段是必需的，类型是字符串
    input: str
    # 'conversation_id' 是可选的
    conversation_id: Optional[str] = None
# @app.post("/api/kb_chat")
# def knowledge_base_chat(payload: KBChatPayload):
#     # FastAPI 会自动验证传入的 JSON 并将其转换为 KBChatPayload 对象
#     # 我们可以直接通过 payload.query 来访问文本框内容
#     user_query = payload.query
#     conversation_id = payload.conversation_id
#
#     print(f"知识库模式接收到问题: '{user_query}'")
#     print(f"会话 ID: {conversation_id}")
#
#     # 模拟处理过程
#     time.sleep(1)
#
#     # 构造并返回一个符合前端期望的 JSON 响应
#     return {
#         "answer": f"我已经收到了您在【知识库模式】下的问题：**{user_query}**。这是一个模拟回复。",
#         "conversation_id": "conv_kb_12345"  # 返回一个新的或更新后的会话ID
#     }
# 测试点
@app.post("/", tags=["Test"])
def test_connection(data):
    """
    一个简单的测试端点，用于验证前后端通信。
    如果能从浏览器或前端成功访问，说明后端服务已启动且可访问。
    """
    print(data)
    print("--- /api/test endpoint was reached! Backend is responsive. ---")
    return JSONResponse(
        status_code=200,
        content={"status": "ok", "message": "你好！后端服务连接成功！"}
    )
